#!/usr/bin/python3
#
# check.py -- Check and fix dependencies and version information in the tinybpt_db.json file
#

import json
import re

def check_info_in_dependencies():
    db_file_path = "data/deploy-packages.json"

    try:
        with open(db_file_path, "r", encoding="utf-8") as db_file:
            data = json.load(db_file)

        for pkg in data.get("packages", []):
            info = pkg.get("info", "")
            dependencies = pkg.get("dependencies", "")
            version = pkg.get("version", "")

            version = re.sub(r'\.(tar\.(gz|bz2|xz)(\.asc|\.sig|\.gpg)?|jar|src\.rock|zip|tgz(\.asc|\.sig)?|orig|NC|src)$', '', version)

            if '/' in version:
                version = version.split('/')[-1]

            pkg["version"] = version

            if info and dependencies:
                dependencies_list = dependencies.split(", ")
                new_dependencies_list = [dep for dep in dependencies_list if dep != info]
                if len(new_dependencies_list) != len(dependencies_list):
                    print(f"Package name with info in dependencies: {pkg.get('name')}")
                    pkg["dependencies"] = ", ".join(new_dependencies_list)

        with open(db_file_path, "w", encoding="utf-8") as db_file:
            json.dump(data, db_file, indent=4)

    except Exception as e:
        print(f"Error reading or processing {db_file_path}: {e}")

if __name__ == "__main__":
    check_info_in_dependencies()